package com.whj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whj.domain.constants.SystemConstants;
import com.whj.domain.dto.AddRoleDTO;
import com.whj.domain.entity.Role;
import com.whj.domain.entity.RoleMenu;
import com.whj.domain.enums.AppHttpCodeEnum;
import com.whj.domain.response.ResponseResult;
import com.whj.domain.vo.PageVo;
import com.whj.domain.vo.RoleVo;
import com.whj.mapper.RoleMapper;
import com.whj.mapper.RoleMenuMapper;
import com.whj.service.RoleMenuService;
import com.whj.service.RoleService;
import com.whj.utils.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 角色信息表(Role)表服务实现类
 *
 * @author wanghaijun
 * @since 2023-05-30 14:46:51
 */
@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Override
    public List<String> selectRoleByUserId(Long id) {
        //判断是否是管理员 如果是返回集合中只需要有admin
        if (id == 1L) {
            List<String> roleKeys = new ArrayList<>();
            roleKeys.add("admin");
            return roleKeys;
        }
        //否则查询用户所具有的角色信息
        return getBaseMapper().selectRoleByUserId(id);
    }

    /**
     * 对角色名进行查询，并分页
     *
     * @param pageNum
     * @param pageSize
     * @param roleName
     * @param status
     * @return
     */
    @Override
    public ResponseResult selectRole(Integer pageNum, Integer pageSize, String roleName, String status) {

        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(roleName), Role::getRoleName, roleName);
        queryWrapper.like(StringUtils.hasText(status), Role::getStatus, status);
        queryWrapper.orderByAsc(Role::getRoleSort);

        Page<Role> page = new Page<>(pageNum, pageSize);
        page(page, queryWrapper);

        return ResponseResult.okResult(new PageVo(page.getRecords(), page.getTotal()));
    }

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 改变状态
     *
     * @param roleVo
     * @return
     */
    @Override
    public ResponseResult roleChangeStatus(RoleVo roleVo) {
        Role role = roleMapper.selectById(roleVo.getRoleId());
        role.setStatus(roleVo.getStatus());
        roleMapper.updateById(role);
        return ResponseResult.okResult();
    }

    @Autowired
    private RoleMenuService roleMenuService;

    /**
     * 新增角色 并更新相关的菜单权限
     *
     * @param addRoleDTO
     * @return
     */
    @Transactional
    @Override
    public ResponseResult addRole(AddRoleDTO addRoleDTO) {
        Role role = BeanCopyUtils.copyBean(addRoleDTO, Role.class);
        roleMapper.insert(role);
        // 添加角色对应的菜单权限
        List<RoleMenu> roleMenus = addRoleDTO.getMenuIds().stream()
                .map(menusId -> new RoleMenu(role.getId(), Long.parseLong(menusId)))
                .collect(Collectors.toList());
        roleMenuService.saveBatch(roleMenus);
        return ResponseResult.okResult();
    }

    /**
     * 通过id查询role
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult selectRoleById(Long id) {
        Role role = roleMapper.selectById(id);
        return ResponseResult.okResult(role);
    }

    @Autowired
    private RoleMenuMapper roleMenuMapper;
    /**
     * 更新role
     *
     * @param addRoleDTO
     * @return
     */
    @Transactional
    @Override
    public ResponseResult updateRole(AddRoleDTO addRoleDTO) {
        Role role = BeanCopyUtils.copyBean(addRoleDTO, Role.class);
        roleMapper.updateById(role);
        List<RoleMenu> roleMenuList = addRoleDTO.getMenuIds()
                .stream()
                .distinct()
                .map( s -> new RoleMenu(role.getId(),Long.parseLong(s)))
                .collect(Collectors.toList());
        LambdaQueryWrapper<RoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleMenu::getRoleId,role.getId());
        roleMenuMapper.delete(queryWrapper);
        roleMenuService.saveBatch(roleMenuList);
        return ResponseResult.okResult();
    }

    /**
     * 查询的是所有状态正常的角色
     *
     * @return
     */
    @Override
    public List<Role> listAllRole() {
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Role::getStatus, SystemConstants.STATUS_NORMAL);
        List<Role> list = list(queryWrapper);
        return list;
    }
}
